package cn.wolfcode.luowowo.community.service.impl;

import cn.wolfcode.luowowo.community.domain.CommunityQuestion;
import cn.wolfcode.luowowo.community.domain.CommunityQuestionTag;
import cn.wolfcode.luowowo.community.mapper.CommunityQuestionContentMapper;
import cn.wolfcode.luowowo.community.mapper.CommunityQuestionMapper;
import cn.wolfcode.luowowo.community.mapper.CommunityQuestionTagMapper;
import cn.wolfcode.luowowo.community.service.ICommunityQuestionService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommunityQuestionServiceImpl implements ICommunityQuestionService {

    @Autowired
    private CommunityQuestionMapper communityQuestionMapper;

    @Autowired
    private CommunityQuestionContentMapper communityQuestionContentMapper;

    @Autowired
    private CommunityQuestionTagMapper communityQuestionTagMapper;

    public List<CommunityQuestion> query() {
        List<CommunityQuestion> questions = communityQuestionMapper.selectForList();
        // 遍历,通过标签id,查对应的标签
        for (CommunityQuestion question : questions) {
            List<CommunityQuestionTag> tagList = new ArrayList<>();
            Long[] idsArr = question.getIdsArr();
            if (idsArr != null) {
                for (Long tagId : idsArr) {
                    CommunityQuestionTag tag = communityQuestionTagMapper.selectByPrimaryKey(tagId);
                    tagList.add(tag);
                }
                question.setTagList(tagList);
            }
        }
        return questions;
    }

    public void save(CommunityQuestion question, UserInfo userInfo) {
        question.setReleaseTime(new Date());
        question.setCreateTime(new Date());
        question.setAuthor(userInfo);
        if (question.getIdsArr() != null) {
            question.setTagsIds(StringUtils.arrayToDelimitedString(question.getIdsArr(), ","));
        }
        communityQuestionMapper.insert(question);
        // 保存问题内容
        if (question.getContent() != null) {
            question.getContent().setId(question.getId());
            communityQuestionContentMapper.insert(question.getContent());
        }
    }

    public CommunityQuestion get(Long id) {
        return communityQuestionMapper.selectByPrimaryKey(id);
    }

    public void addQuestionViewnum(Long questionId, int count) {
        communityQuestionMapper.addViewnum(questionId, count);
    }

    public void addReplynum(Long id, int count) {
        communityQuestionMapper.addReplynum(id, count);
    }
}
